﻿using CommonServiceLocator;
using Communication;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Jn698._45GWTool.ModelViews;
using Jn698._45GWTool.Services;
using Jn698._45GWTool.Views;
using nblTool.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WebFirst.Entities;
using WindowsFormsApp1.Utils;

namespace Jn698._45GWTool.ViewModels.Controls
{
    public class CommonControlViewModel:ViewModelBase
    {
        private GWTempFrameService gWTempFrameService = new GWTempFrameService();
        private SerialPortHelper serialPortHelper = SerialPortHelper.Instance;
        public List<GWTempFrame> gWTempFrames = new List<GWTempFrame>();
        #region 属性
        private string control="43";

		public string Control
		{
			get { return control; }
			set { Set(ref control, value); }
        }

		private string userData;

		public string UserData
		{
			get { return userData; }
			set { Set(ref userData,value); }
		}


		private string frameLen;

		public string FrameLen
		{
			get { return frameLen; }
			set { Set(ref frameLen,value); }
		}

		private string frameAddress;

		public string FrameAddress
		{
			get { return frameAddress; }
			set { Set(ref frameAddress,value); }
		}

		private string hCS;

		public string HCS
		{
			get { return hCS; }
			set { Set(ref hCS,value); }
		}

        private string fCS;

        public string FCS
        {
            get { return fCS; }
            set { Set(ref fCS, value); }
        }

		private string frame;

		public string Frame
		{
			get { return frame; }
			set { Set(ref frame,value); }
		}

        private bool satae=true;

        public bool State
        {
            get { return satae; }
            set { Set(ref satae, value); }
        }

        #endregion

        #region ctor
        public CommonControlViewModel()
        {
            gWTempFrames = gWTempFrameService.Select();
            if (gWTempFrames?.Count>0)
            {
                UserData = gWTempFrames[0].FrameData;
            }
        }
        #endregion
        #region Command
        public RelayCommand GetFrameCommand
		{
			get
			{
                var command = new RelayCommand(() =>
				{
                    if (MainViewModel.selectedDevice == null)
                    {
                        MessageBox.Show("请选择设备");
                        return;
                    }
                    switch (ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex)
                    {

                        //明文+RN_MAC
                        case 2:
                        //明文+SID_MAC
                        case 3:
                        //密文+SID
                        case 4:
                        //密文+SID_MAC
                        case 5:
                            if (string.IsNullOrWhiteSpace(AppControlViewModel.SessionInitKey))
                            {
                                MessageBox.Show("请先建立应用连接");
                                return;
                            }
                            break;
                        //明文
                        case 0:
                        //明文+RN
                        case 1:
                        default:

                            break;
                    }
                    byte[] byteAddress = StringUtils.strToHexByte(MainViewModel.selectedDevice.DeviceAddress);
                    //List<byte> APDU = GetSetAPDU(mode, map, isDateTimeFlag); GetSecuriityFrame
                    //List<byte> APDU = GetSecuriityFrame(GetSetAPDU(mode, map, isDateTimeFlag));
                    List<byte> APDU;
                    if (string.IsNullOrWhiteSpace(UserData))
                    {
                        MessageBox.Show("请输入用户数据");
                        return;
                    }
                    APDU = MessageGenerationModule.GetSecuriityFrame(StringUtils.hexStringToBytes(UserData.Replace(" ", string.Empty)).ToList());
                    //定义临时字节列表
                    List<byte> temp = new List<byte>();
                    
                    temp.Add(0x68);
                    //长度域
                    short length = (short)(2 + 1 + 1 + (short)byteAddress.Length + 1 + 2 + (short)APDU.Count + 2);
                    FrameLen = string.Format("{0:X2}{1:X2}",length&0x00ff, length>>8);
                    byte[] byteLength = BitConverter.GetBytes(length);

                    temp.AddRange(byteLength);

                    //控制域
                   
                    byte control = StringUtils.string_2_BCD(Control)[0];
                    temp.Add(control);

                    //地址域
                    //服务器地址SA

                    temp.Add((byte)(byteAddress.Length - 1));
                    
                    Array.Reverse(byteAddress);
                    temp.AddRange(byteAddress);
                   
                    //客户机地址CA
                    byte ca = 0x11;
                    temp.Add(ca);
                    
                    //帧头校验HCS
                    HCS = ByteUtils.bytesToHexString(CheckSum.CRC16(temp, 1));
                    temp.AddRange(CheckSum.CRC16(temp, 1));
                    
                    //链路用户数据
                    temp.AddRange(APDU);
                    
                    //帧校验FCS
                    FCS = ByteUtils.bytesToHexString(CheckSum.CRC16(temp, 1));
                    temp.AddRange(CheckSum.CRC16(temp, 1));

                    //结束字符
                    temp.Add(0x16);
                    Frame = ByteUtils.bytesToHexString(temp);
                });
				return command;
			}
		}

        public RelayCommand SaveCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    ServiceLocator.Current.GetInstance<FrameMessageInfoViewModel>().Name = string.Empty;
                    if (new FrameMessageInfoView().ShowDialog()==true)
                    {
                        GWTempFrame gWTempFrame = new GWTempFrame();
                        gWTempFrame.FrameName = ServiceLocator.Current.GetInstance<FrameMessageInfoViewModel>().Name;
                        gWTempFrame.FrameData = UserData;
                        gWTempFrameService.Insert(gWTempFrame);
                    }
                });
                return command;
            }
        }

        public RelayCommand LoadCommand
        {
            get
            {
                var command = new RelayCommand(() => 
                {
                    if (new FrameShowView().ShowDialog() == true)
                    {
                        
                        int index = ServiceLocator.Current.GetInstance<FrameShowViewModel>().SelectedIndex;
                        gWTempFrames = gWTempFrameService.Select();
                        GWTempFrame gWTempFrame = gWTempFrames[index];
                        UserData= gWTempFrame.FrameData;
                    }
                });
                return command;
            }
        }

        public RelayCommand SendCommand
        {
            get
            {
                var command = new RelayCommand(() => {
                    Task.Run(async () =>
                    {
                        State = false;
                        byte[] b = StringUtils.hexStringToBytes(Frame);
                        string msgStr = "";
                        for (int i = 0; i < b.Length; i++)
                        {
                            msgStr += b[i].ToString("X2") + " ";
                        }
                        Messenger.Default.Send<string>($"发送帧({DateTime.Now.ToString()})：{msgStr}", "SendMessage");

                        serialPortHelper.SendDataMethod(b);
                        bool result = false;
                        await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                        State = true;
                    });
                });
                return command;
            }
        }

        #endregion
    }

}
